class EventsController < ApplicationController
	def create
		@event = Event.new(event_params)

		if @event.save
			redirect_to @event
		else
			render 'new'
		end
	end
	
	def all
		queryed_dates = Event.distinct.pluck(:date).map { |d| d.strftime('%b %Y') }
		@dates =  queryed_dates.push( Date.today().strftime('%b %Y') ).uniq.sort { |a, b| Date.parse('1st '+a) <=> Date.parse('1st '+b)}
		
		if params[:date] != nil && @dates.include?( params[:date] )
			@selected_date = params[:date]
		else
			@selected_date = Date.today().strftime('%b %Y')
		end
		
		object_date = Date.parse('1st '+@selected_date)
		@events = Event.where("date >= ? AND date < ?", object_date, object_date.next_month)
		
		selected_date_index = @dates.index(@selected_date)
		
		@is_there_prev_date = selected_date_index != nil && selected_date_index > 0
		@prev_date = @dates.fetch( selected_date_index - 1, nil )
		
		@is_there_next_date = selected_date_index != nil && selected_date_index < @dates.size()-1
		@next_date = @dates.fetch( selected_date_index + 1, nil )
		
	end


	def best
		@events = Event.where(best: true).order(date: :desc)
	end

	def show
		@event = Event.find(params[:id])
		@related_structures = @event.structures

		@guided_tour = params[:guided_tour] == 'true'

		if @guided_tour && @event.best != true
		######## more quietly:
		#	params[:guided_tour] = false
		#	@guided_tour = false

			raise "Illigal URL: Event not valid for guided tour"
		end
		
		if @guided_tour
			@best_events = Event.where(best: true)
			current_index	= @best_events.index(@event)
			previous_index 	= (current_index-1)%@best_events.size()
			next_index		= (current_index+1)%@best_events.size()

			@previous 	= @best_events.at(previous_index)
			@next 		= @best_events.at(next_index)
		end
	end

	def destroy
		@event = Event.find(params[:id])
		@event.destroy

		redirect_to events_all_path
	end

	def hd_photos
		@event = Event.find(params[:id])
		@hd_photos = @event.hd_photos
		@guided_tour = params[:guided_tour] == 'true'
	end

	def add_structure
		@booking = Booking.new
	end


	private
		def event_params
			params.require(:event).permit(:name, :date, :description, :img_src, :preview_img_src, :schedule, :best)
		end

end
